package com.mjt.admin.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.mjt.admin.model.CaptchaImageModel;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

/**
 * @author shkstart
 * @create 2021-10-28 9:42
 */
@RestController
public class CaptchaController {

    @Resource
    private DefaultKaptcha defaultKaptcha;


    /**
     * @description
     * @author 莫某人
     * @date 9:46 2021/10/28
     * @param session
     * @return {@link }
     * @throws IOException
     **/
    @GetMapping("/image")
    public void kaptcha(HttpSession session, HttpServletResponse response) throws IOException {
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        //获取生成燕子吗文字
        String captext=defaultKaptcha.createText();

        //将验证码cunrusession并设置过期时间
        session.setAttribute("captcha_key",new CaptchaImageModel(captext,2*60));

        ServletOutputStream os = response.getOutputStream();

        BufferedImage bufferedImage=defaultKaptcha.createImage(captext);

        ImageIO.write(bufferedImage,"jpg",os);
        os.flush();


    }



}
